<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item,index) in levelList" :key="item.path || item.name">
        <span v-if="item.redirect === 'noRedirect' || index === levelList.length - 1" class="no-redirect">{{ item.meta.title }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script setup>
import {ref, watch} from 'vue'
import {useRoute, useRouter} from 'vue-router'

const route = useRoute()
const router = useRouter()
const levelList = ref(null)

const getBreadcrumb = () => {
  // 只显示带有 meta.title 的路由
  let matched = route.matched.filter(item => item.meta && item.meta.title)
  const first = matched[0]
  if (!isDashboard(first)) {
    matched = [{path: '/dashboard', meta: {title: '首页'}}].concat(matched)
  }
  levelList.value = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
}

const isDashboard = (route) => {
  const path = route && route.path
  if (!path) {
    return false
  }
  return path.trim() === '/dashboard'
}

getBreadcrumb()

const handleLink = (item) => {
  const {redirect, path} = item
  if (redirect) {
    router.push(redirect)
    return
  }
  router.push(path)
}

watch(route, (route) => {
  // 如果是转到重定向页面，不需要更新面包屑
  if (route.path.startsWith('/redirect/')) {
    return
  }
  getBreadcrumb()
})
</script>

<style scoped>
.app-breadcrumb.el-breadcrumb {
  font-size: 14px;
  margin-left: 8px;
  margin-bottom: 1.25rem;
}

.app-breadcrumb .no-redirect {
  color: #97a8be;
  cursor: text;
}
</style>
